#include "logmanagement.h"
#include <QScrollBar>
#include <QScroller>
#include <QStandardItem>
#include <QStyledItemDelegate>
#include <QPainter>
#include <QDateTime>
#include <mainwindow.h>
#include <transparentbutton.h>
#include <QTabBar>
#include "models/operatelogmodel.h"
#include <models/warninglogmodel.h>

// 创建自定义委托类
class LogItemDelegate : public QStyledItemDelegate {
public:
    explicit LogItemDelegate(QObject *parent,LogType lType):QStyledItemDelegate(parent),logType(lType){ }
    void paint(QPainter *painter, const QStyleOptionViewItem &option,
               const QModelIndex &index) const override {
        QStyleOptionViewItem opt = option;
        initStyleOption(&opt, index);
        // 设置背景色
        painter->fillRect(opt.rect,
                          index.row() % 2 == 0 ? QColor("#252627") : QColor("#2E2F31"));

        // 计算各列的矩形区域
        QRect numRect;
        QRect timeRect;
        QRect logRect;
        QRect robotRect;
        if(logType==OPERATE)
        {
            numRect=QRect(opt.rect.left() + 28*g_xScale, opt.rect.top(), 80*g_xScale, opt.rect.height());
            timeRect=QRect(numRect.right() , opt.rect.top(), 300*g_xScale, opt.rect.height());
            logRect=QRect(timeRect.right() , opt.rect.top(),
                            opt.rect.width() - numRect.width() - timeRect.width() - 28*g_xScale,
                            opt.rect.height());
        }
        else
        {
            numRect=QRect(opt.rect.left() + 28*g_xScale, opt.rect.top(), 80*g_xScale,opt.rect.height());
            robotRect=QRect(numRect.right()  , opt.rect.top(), 300*g_xScale,opt.rect.height());
            timeRect=QRect(robotRect.right(), opt.rect.top(),300*g_xScale,opt.rect.height());
            logRect=QRect(timeRect.right(), opt.rect.top(),
                            opt.rect.width() - numRect.width() - timeRect.width()
                                - robotRect.width()- 28*g_xScale,
                            opt.rect.height());
        }
        // 设置文本颜色和字体
        painter->setPen(QColor("#CCCCCC"));
        QFont font;
        font.setFamily("微软雅黑");
        font.setPixelSize(int(18*g_xScale));

        painter->setFont(font);
        if(logType==OPERATE)
        {
            // 绘制文本
            painter->drawText(numRect, Qt::AlignCenter, QString::number(index.row()+1));
            painter->drawText(timeRect, Qt::AlignCenter, index.data(OperateLogModel::TimeRole).toString());
            painter->drawText(logRect, Qt::AlignCenter, index.data(OperateLogModel::LogRole).toString());
        }
        else
        {
            // 绘制文本
            painter->drawText(numRect, Qt::AlignCenter, QString::number(index.row()+1));
            painter->drawText(timeRect, Qt::AlignCenter, index.data(WarningLogModel::TimeRole).toString());
            painter->drawText(robotRect, Qt::AlignCenter, index.data(WarningLogModel::RobotRole).toString());
            painter->drawText(logRect, Qt::AlignCenter, index.data(WarningLogModel::LogRole).toString());
        }
    }
    QSize sizeHint(const QStyleOptionViewItem &option,
                   const QModelIndex &index) const override {
        Q_UNUSED(index);
        return QSize(option.rect.width(), 45*g_xScale);
    }
private:
    LogType logType;
};

LogManagement::LogManagement(QWidget *parent)
    : QWidget(parent)
{
    initUI();
    connect(WarningLogModel::getInstance(),&WarningLogModel::rowsInserted, this, &LogManagement::onRowsInserted);
}

void LogManagement::initUI()
{
    // 设置背景颜色和全局字体
    setStyleSheet(
        "QWidget {"
        "    background-color: #1F1F1F;"
        "    font-family: '微软雅黑';"
        "}"
        );

    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);
    // 创建头部区域
    QWidget *headerWidget = new QWidget(this);
    headerWidget->setFixedHeight(60*g_yScale);
    QHBoxLayout *titleLayout = new QHBoxLayout(headerWidget);
    titleLayout->setContentsMargins(28*g_xScale, 0, 28*g_xScale, 0);
    // 创建标题标签
    m_pOperationLogBtn = new TouchButton("操作日志");
    m_pOperationLogBtn->setCheckable(true);
    m_pOperationLogBtn->setChecked(true);
    m_pAlarmLogBtn = new TouchButton("告警日志");
    m_pAlarmLogBtn->setCheckable(true);
    m_pCleanBtn = new TouchButton("清除日志");
    m_pCleanBtn->setVisible(false);

    QString style= QString("QPushButton {"
                            "background-color: #00000000;"
                            "color: white ;"
                            "border: none;"
                            "font: %1px \"微软雅黑\";}"
                            "QPushButton:checked{"
                            "color:#0056b3;}").arg(int(20*g_xScale));
    m_pOperationLogBtn->setStyleSheet(style);
    m_pAlarmLogBtn->setStyleSheet(style);
    m_pCleanBtn->setStyleSheet(QString("QPushButton{"
                                       "background:transparent;"
                                       "color:#007BFF;"
                                       "font:%1px \"微软雅黑\";"
                                       "border-color: #098CFF;"
                                       "border-width:1px;}"
                                       "QPushButton:pressed{"
                                       "color:#0056b3;}").arg(int(20*g_xScale)));
    connect(m_pCleanBtn,&QPushButton::clicked, this, &LogManagement::onCleanClicked);
    m_pButtonGroup=new QButtonGroup(this);
    m_pButtonGroup->setExclusive(true);
    m_pButtonGroup->addButton(m_pOperationLogBtn,OPERATE);
    m_pButtonGroup->addButton(m_pAlarmLogBtn,WARNING);
    connect(m_pButtonGroup,SIGNAL(buttonToggled(int,bool)), this, SLOT(onSwitchPage(int,bool)));
    QLabel *label = new QLabel("|");
    label->setStyleSheet(QString("color: #48494E;""font:%1px \"微软雅黑\";").arg(int(20*g_xScale)));
    label->setFixedWidth(5*g_xScale);  // 改为最小宽度
    label->setAlignment(Qt::AlignCenter);

    titleLayout->addWidget(m_pOperationLogBtn);
    titleLayout->addWidget(label);
    titleLayout->addWidget(m_pAlarmLogBtn);
    titleLayout->addStretch();
    titleLayout->addWidget(m_pCleanBtn);

    tabWidget=new QTabWidget(this);
    tabWidget->tabBar()->setVisible(false);
    tabWidget->setDocumentMode(true);
    operateListView = new QListView;
    warningListView = new QListView;
    operateListView->setModel(OperateLogModel::getInstance());
    operateListView->setItemDelegate(new LogItemDelegate(this,OPERATE));
    warningListView->setModel(WarningLogModel::getInstance());
    warningListView->setItemDelegate(new LogItemDelegate(this,WARNING));

    tabWidget->addTab(createList(operateListView,OPERATE),"操作");
    tabWidget->addTab(createList(warningListView,WARNING),"告警");
    mainLayout->addWidget(headerWidget);
    mainLayout->addWidget(tabWidget);
}

QWidget *LogManagement::createList(QListView *listView, LogType lType)
{
    QWidget *listWidget= new QWidget(tabWidget);
    QVBoxLayout *listLayout = new QVBoxLayout(listWidget);
    listLayout->setContentsMargins(0, 0, 0, 0);
    listLayout->setSpacing(0);

    // 在添加 ListView 之前，创建表头
    QWidget *tableHeader = new QWidget;
    tableHeader->setFixedHeight(50*g_xScale);
    tableHeader->setStyleSheet("background-color: #2E2F31;");

    QHBoxLayout *headerLayout = new QHBoxLayout(tableHeader);
    headerLayout->setContentsMargins(28*g_xScale, 0, 28*g_xScale, 0);
    headerLayout->setSpacing(0);  // 添加列间距

    QString labelStyle=QString("QLabel{color: white;font: %1px \"微软雅黑\";}").arg(int(20*g_xScale));
    // 创建表头标签
    QLabel *numHeader = new QLabel("序号");
    numHeader->setStyleSheet(labelStyle);
    numHeader->setFixedWidth(80*g_xScale);
    numHeader->setAlignment(Qt::AlignCenter);

    QLabel *robotHeader = new QLabel("机器人");
    robotHeader->setStyleSheet(labelStyle);
    robotHeader->setFixedWidth(300*g_xScale);  // 改为最小宽度
    robotHeader->setAlignment(Qt::AlignCenter);
    QLabel *timeHeader = new QLabel("时间");
    timeHeader->setStyleSheet(labelStyle);
    timeHeader->setFixedWidth(300*g_xScale);  // 改为最小宽度
    timeHeader->setAlignment(Qt::AlignCenter);
    QLabel *operHeader = new QLabel(lType==OPERATE?"告警":"操作");
    operHeader->setStyleSheet(labelStyle);
    operHeader->setMinimumWidth(1000*g_xScale);  // 设置最小宽度
    operHeader->setAlignment(Qt::AlignCenter);

    headerLayout->addWidget(numHeader);
    if(lType==WARNING)
        headerLayout->addWidget(robotHeader, 1);
    headerLayout->addWidget(timeHeader, 1);        // 添加拉伸因子
    headerLayout->addWidget(operHeader, 1);        // 添加拉伸因子


    listView->setVerticalScrollMode(QListView::ScrollPerPixel);
    QScroller::grabGesture(listView, QScroller::LeftMouseButtonGesture);
    listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    listView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    // 设置ListView样式
    listView->setStyleSheet(QString(
                                "QListView {"
                                "background-color: #1F1F1F;"
                                "border: none;"
                                "font: %1px \"微软雅黑\";}"
                                "QListView::item {"
                                "height: %2px;"
                                "background-color: #252627;"
                                "border: none;"
                                "color: white;"
                                "font: %1px \"微软雅黑\";}"
                                "QListView::item:alternate {"
                                "    background-color: #2E2F31;}"
                                "QListView::item:selected {"
                                "    background-color: #1E90FF;}"
                                "QListView::item:hover {"
                                "    background-color: #3E4145;}"
                                "QScrollBar:vertical {"
                                "    background-color: #1F1F1F;}"
                                "QScrollBar::handle:vertical {"
                                "    background-color: #4A4A4A;}").arg(int(18*g_xScale)).arg(int(50*g_xScale)));

    listView->setAlternatingRowColors(true);
    listView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    listView->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    listView->setSelectionMode(QAbstractItemView::SingleSelection);
    listView->setSelectionBehavior(QAbstractItemView::SelectRows);
    listLayout->addWidget(tableHeader);   // 添加表头
    listLayout->addWidget(listView);      // 添加列表视图
    return listWidget;
}


void LogManagement::onSwitchPage(int nID, bool b)
{
    if(b)
        tabWidget->setCurrentIndex(nID);
    if(nID==OPERATE)
        m_pCleanBtn->setVisible(false);
    else
        m_pCleanBtn->setVisible(true);
}

void LogManagement::onRowsInserted(const QModelIndex &parent, int first, int last)
{
    Q_UNUSED(parent);
    Q_UNUSED(first);
    Q_UNUSED(last);
    QScrollBar *scrollBar = warningListView->verticalScrollBar();
    int maxValue = scrollBar->maximum();
    int pageStep = scrollBar->pageStep();
    int nVal = scrollBar->value();
    if (nVal + pageStep >= maxValue-100*g_xScale) {
        warningListView->scrollToBottom();
    }
}
void LogManagement::onCleanClicked()
{
    WarningLogModel::getInstance()->deleteDatas();
}

void LogManagement::setVisible(bool visible)
{
    if(!visible)
    {
        m_pOperationLogBtn->setChecked(true);
    }
    QWidget::setVisible(visible);
}

void LogManagement::showEvent(QShowEvent *event)
{
    operateListView->scrollToBottom();
    warningListView->scrollToBottom();
    QWidget::showEvent(event);
}
